<template>
  	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">
    <el-form id="page_order_create" ref="form" :model="form" :rules="rules" v-loading="loading"
      class="common-form-row common-form-panel-div-right" label-position="right" label-width="140px"
      style="margin-bottom: 90px;">

      <ex_header_spiler :title="$tt('label_customer_info')"></ex_header_spiler>

      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_customer')" prop="customerId" key="customerId">
            <common_customer_choose :value="form.customerId"
              :currentLabel="form.customerId ? $formatNameCode(form.customerName, form.customerCode) : null"
              @changeItem="customerChange" :disabled="edit" style="width: 100%;"></common_customer_choose>
          </el-form-item>
        </el-col>
      </el-row>

      <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_outbound_code')" prop="outOrderNo" ref="form_outOrderNo">
            <div class="flex_row_center form_input_big">
              <el-input v-model="outOrderNoTemp" :disabled="outOrderNoLock" :placeholder="$tt('label_outbound_code')">
                <el-button slot="prepend" icon="el-icon-edit" v-if="outOrderNoLock && !edit"
                  @click="modifyOutOrder"></el-button>
              </el-input>
              <el-button icon="el-icon-search" type="primary" class="mg_l2" @click="getOutOrderInfo"
                :disabled="outOrderNoTemp == form.outOrderNo">{{ $tt('label_search') }}</el-button>
            </div>
            <div class="color_warning text_small bold" v-if="outOrderNoTemp != form.outOrderNo">
              {{ $tt('tip_no_search_outbound_code') }}</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_returnGood_track_code')" prop="trackingNumber">
            <ex_super_input v-model="form.trackingNumber" class="form_input_big" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_returnGood_warehouse')" prop="warehouseId">
            <base_warehouse_select :value="form.warehouseId" class="w_fill form_input_big"
              @changeItem="changeReturnWarehouse" />
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="3">
          <el-form-item :label="$tt('label_return_order_sku')" prop="detailList">
            <ex_super_table v-bind="skuTableOption" :data="outOrderSkus" ref="TableSkuList"
              @selection-change="e => selection = e" height="400">
            </ex_super_table>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <el-form-item :label="$tt('label_return_order_image')" prop="attachedList">
            <ex_super_upload v-model="form.attachedList" accept=".png,.jpg" :limit="5" />
          </el-form-item>
        </el-col>
      </el-row>



    </el-form>
  </div>
	<div class="page_rela_bottom_area" >
      <el-button type="primary" @click="submit('TO_BE_RECEIVED')">{{ $tt('label_submit') }}</el-button>
      <el-button type="primary" @click="save('DRAFT')">{{ $tt('label_save') }}</el-button>
      <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
    </div>


    <el-dialog :title="$tt('label_submit_return_code')" :visible.sync="dialogTip" custom-class="dialog_default"
      @close="return_page_back">
      <div>
        <div>
          {{ $tt("label_return_order_code") }}：{{ dialogTipInfo.orderNo }}
        </div>
        <div>
          {{ $tt("label_mark_code_RMA") }}：{{ dialogTipInfo.identificationCode }}
        </div>
        <div>
          {{ $tt("label_consignee_person_name") }}：{{ dialogTipInfo.contacter }}
        </div>
        <div>
          {{ $tt("label_consignee_person_phone") }}：{{ dialogTipInfo.phone }}
        </div>
        <div>
          {{ $tt('label_return_good_address') }}：{{ dialogTipInfo.streetAddress1 }}
        </div>
        <div>
          {{ $tt('tip_return_new_order_show') }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="e => {
          dialogTip = false
        }">{{ $tt('label_confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

let default_obj = {
  customerId: null,//		string 	客户ID
  customerCode: null,//		string 	客户编号
  status: 'DRAFT',
  outOrderNo: '',//原出库单号
  orderType: "MIXED_RETURN",
  trackingNumber: null,//		string 	退运追踪号码
  returnType: 'CUSTOMER',
  bizType: 'TOC',
  packageQuantity: 1,
  warehouseId: null,

  productId: '001',
  productCode: "test",
  productName: "test",
  detailList: [],
  attachedList: [],
}
import router_params from '@/mixin/router_params';
import Schema from 'async-validator'

export default {
  mixins: [router_params],
  components: {},

  data() {
    return {
      dialogTip: false,
      dialogTipInfo: {},
      edit: false,
      loading: false,
      selection: [],
      outOrder: null,
      outOrderSkus: [],
      outOrderNoLock: false,
      imgurl: "",
      outOrderNoTemp: "",
      form: _.cloneDeep(default_obj),

      sku_descriptor: new Schema({
        skuReturnQuantity: { type: 'number', message: this.$tt('tip_can_no_empty'), required: true, },
        returnHandlingMethod: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, }
      }),
      rules: {
        customerId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        outOrderNo: {
          required: true, trigger: 'blur', message: this.$tt('tip_can_no_empty'),
        },
        orderType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        warehouseId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        warehouseId: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        detailList: {
          trigger: 'blur', type: 'array',
          validator: (r, v, cb) => {
            if (_.isEmpty(this.selection) && !_.isEmpty(this.outOrderSkus)) {
              cb(this.$tt('tip_please_add_least_one_sku'))
            } else {
              if (_.isEmpty(this.selection)) {
                cb()
              } else {
                let check = true
                this.selection.forEach(it => {
                  this.sku_descriptor.validate(it, (errors, fields) => {
                    this.$set(it, 'error', {})
                    if (errors) {
                      errors.forEach(er => {
                        this.$set(it.error, er.field, er.message)
                      })
                      check = false
                    }
                  })
                })
                if (check) {
                  cb()
                } else {
                  cb(this.$tt('label_sku_specification_check_fail'))

                }
              }


            }

          }
        },
      },
      skuTableOption: {
        model: [
          {
            type: 'selection', clickToggle: true,
            clickExclude: ['skuReturnQuantity', 'returnHandlingMethod'], keyGroup: 'label_table_operate'
          },

          {
            key: 'skuNameCn', label: 'label_sku_info', 'width': 120, 'show-overflow-tooltip': true,
          },
          { key: 'skuBarcode', label: 'label_sku_code', 'min-width': 130, 'show-overflow-tooltip': true, },
          {
            key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': 150, 'show-overflow-tooltip': true,
          },
          {
            key: 'declaredValue', label: 'label_declared_value', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
          },
          {
            key: 'skuCount', label: 'label_outbound_count', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v) => r.actualOutCount || r.skuCount,


          },
          {
            key: 'skuReturnQuantity', label: 'label_return_order_count', 'width': 140,
            render: (h, { row }) => {
              if (!this.selection.includes(row)) return
              return h('ex_bottom_tip_item', {
                props: {
                  tip: row.error && row.error.skuReturnQuantity,
                },
              }, [
                h('el-input-number', {
                  class: 'w_fill',
                  props: {
                    min: 1, max: row.skuCount,
                    'step-strictly': true,
                    step: 1,
                    value: row.skuReturnQuantity
                  },
                  on: {
                    input: (e) => this.$set(row, 'skuReturnQuantity', e)
                  }
                })
              ])

            }
          },
          {
            key: 'returnHandlingMethod', label: 'label_do_with_method', 'width': 160,
            render: (h, { row }) => {
              if (!this.selection.includes(row)) return
              return h('ex_bottom_tip_item', {
                props: {
                  tip: row.error && row.error.returnHandlingMethod,
                },
              }, [
                h('ex_select_auto', {
                  class: 'w_fill',
                  props: {
                    enum: 'SkuReturnMethodEnum',
                    listHandler: (list) => {
                      return list.filter(it => ['DELETE', 'PUT_SHELF', 'DEFECTIVE'].includes(it))
                    },
                    value: row.returnHandlingMethod,
                  },
                  on: {
                    input: (e) => this.$set(row, 'returnHandlingMethod', e)
                  }
                })
              ])

            }
          },
        ]
      },

    };
  },

  methods: {
    productChange(e) {
      if (!e) e = { productId: null, productName: null, productCode: null }
      this.$set(this.form, 'productId', e.productId)
      this.$set(this.form, 'productCode', e.productCode)
      this.$set(this.form, 'productName', e.productName)
    },

    changeReturnWarehouse(e) {
      this.$set(this.form, 'warehouseId', e.id)
      this.$set(this.form, 'warehouseCode', e.code)
      this.$set(this.form, 'warehouseName', e.name)
    },
    customerChange(e) {
      if (e) {
        if (this.outOrder) {
          this.$confirm(this.$tt('tip_confirm_modify_customer_will_remove_outbound_info'), this.$tt("label_tip"), {
            type: 'warning'
          }).then(() => {
            this.form.customerId = e.customerId
            this.form.customerName = e.customerName
            this.form.customerCode = e.customerCode
            this.outOrder = null
            this.form.outOrderNo = null
            this.outOrderSkus = []
            this.outOrderNoLock = false
          }).catch(() => {

          });
        } else {
          this.form.customerId = e.customerId
          this.form.customerName = e.customerName
          this.form.customerCode = e.customerCode
        }


      }
    },
    modifyOutOrder() {
      this.$confirm(this.$tt('tip_confirm_modify_code_will_remove_outbound_info'), this.$tt("label_tip"), {
        type: 'warning'
      }).then(() => {
        this.outOrder = null
        this.form.outOrderNo = null
        this.outOrderSkus = []
        this.outOrderNoLock = false
      }).catch(() => {

      });
    },
    getOutOrderInfo(e, call) {
      if (!this.form.customerId) return this.$message.warning(this.$tt("tip_please_select_first_operate_customer"))
      this.loading = true
      this.$ajax({
        url: this.$url['oms/outboundDetailByCode'],
        method: 'post',
        data: { orderNo: this.outOrderNoTemp },
        success: (res) => {
          if (res && res.data) {
            if (this.form.customerId !== res.data.customerId) return this.$message.warning(this.$tt("tip_customer_do_match_outbound_order"))
            if (['COMPLETE_OUTBOUND', 'COMPLETED'].includes(res.data.outStatus)) {
              this.outOrder = res.data
              res.data.detailList.forEach(it => {
                delete it.id
              })
              this.outOrderSkus = res.data.detailList
              this.initSkuDetail(this.outOrderSkus)
              delete res.data.detailList
              this.form.outOrderNo = this.outOrderNoTemp
              this.outOrderNoLock = true
              if (call) {
                this.$nextTick(() => {
                  call(this.outOrderSkus)
                })
              }
              return
            } else {
              return this.$message.error(this.$tt('tip_status_error_no_operate'))
            }
          }
          return this.$message.error(this.$tt('tip_not_found_data'))
        },
        complete: () => {
          this.loading = false
        }
      })
    },

    initSkuDetail(list) {
      this.loading = true
      this.$ajax({
        url: this.$url['mms/skuDetails'],
        method: 'post', type: "json",
        data: { idList: _.uniq(list.map(it => it.skuId)) },
        success: (res) => {
          this.$refs.form_outOrderNo.clearValidate()
          this.outOrderSkus.forEach(sku => {
            if (!sku.returnHandlingMethod) {
              const orgSku = _.find(res.data.rows, it => it.id == sku.skuId)
              if (!!orgSku.skuReturnMethod) {
                this.$set(sku, 'returnHandlingMethod', orgSku.skuReturnMethod)
              }
            }
          }
          )
        },
        complete: () => {
          this.loading = false
        }
      })
    },


    init_data_default(into_params) {
      this.form = _.cloneDeep(default_obj)
      this.edit = !!into_params.edit
      if (this.edit) {
        if (into_params.id) {
          this.loading = true
          this.$ajax({
            url: this.$url['oms/ReturnOrderDetail'],
            method: 'post',
            data: { id: into_params.id },
            success: (res) => {
              if (into_params.copy) {
                delete res.data.id
                this.edit = false
              }
              // res.data.attachedList = res.data.orderAttachmentLists
              // delete res.data.orderAttachmentLists

              const { detailList, ...form } = res.data
              this.form = form
              if (detailList) {
                this.outOrderSkus = detailList.map(it => {
                  it.skuNameCn = it.skuName
                  it.currencyCode = it.skuCurrencyCode
                  it.declaredValue = it.skuDeclaredValue
                  it.skuCount = it.skuQuantity
                  return it
                })
              }
              if (res.data.outOrderNo) {
                this.outOrderNoTemp = this.form.outOrderNo
                this.getOutOrderInfo(null, (list) => {
                  list.forEach(it => {
                    const skus = detailList.filter(sku => sku.skuId == it.skuId)
                    if (!_.isEmpty(skus)) {

                      it.skuReturnQuantity = _.reduce(skus, (r, it) => this.$math_add(r, (it.skuReturnQuantity)), 0)
                      it.returnHandlingMethod = _.head(skus).returnHandlingMethod
                      it.id = _.head(skus).id
                      this.$refs.TableSkuList.toggleRowSelection(it, true)
                    }
                  })

                })
              }
              this.fixTabLabel()
            },
            complete: () => {
              this.loading = false
            }
          })
        }
      }
      this.fixTabLabel()
    },
    fixTabLabel() {
      if (this.edit && !!this.form.id) {
        this.$emit("tagModifyLabel", { _key: 'label_name_code', name: this.$tt('label_edit_return_order'), code: this.form.trackingNumber || '' })
      } else {
        this.$emit("tagModifyLabel", "label_new_return_order")
      }
    },

    getSubmitData() {
      const data = _.cloneDeep(this.form)
      if (data.attachedList) {
        data.attachedList = data.attachedList.map(it => {
          return {
            fileType: it.fileExt || it.fileType,
            filePath: it.filePath,
          }
        })
      }
      data.detailList = this.selection.map(it => {
        it.skuCode = it.skuBarcode
        it.skuName = it.skuNameCn
        it.currencyType = it.currencyCode
        it.skuCurrencyCode = it.currencyCode
        it.skuDeclaredValue = it.declaredValue
        it.skuQuantity = it.actualOutCount || it.skuCount
        return it
      })
      if (this.outOrder && !data.senderAddressParam) {
        data.senderAddressParam = {
          country: this.outOrder.country,
          province: this.outOrder.province,//	string 	省份
          city: this.outOrder.city,//	string 	城市
          county: this.outOrder.county,//	string 	区县
          address1: this.outOrder.address,//	string 	地址1
          address2: this.outOrder.reserveAddress,//	string 	地址2
          consignee: this.outOrder.consignee,//	string 	名称
          consigneePhone: this.outOrder.consigneePhone,//		string 	电话
          consigneeEmail: this.outOrder.email,//		string 	邮箱
          postcode: this.outOrder.postcode,//string 	邮编
          houseNumber: this.outOrder.houseNumber,//	string 	门牌号
          companyName: this.outOrder.companyName,//	string 	公司名称
        }
        // data.productId = this.outOrder.logisticsId
        // data.productCode = this.outOrder.logisticsCode
        // data.productName = this.outOrder.logisticsName
      }
      return data
    },
    save() {
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          const data = _.cloneDeep(this.form)
          this.$ajax({
            url: this.$url['oms/ReturnOrderSave'],
            method: 'post',
            type: 'json',
            loading: true,
            data: this.getSubmitData(),
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.return_emit(null, "reload")
              this.return_page_back()
            }
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },

    submit() {
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          this.$ajax({
            url: this.$url['oms/ReturnOrderSubmit'],
            method: 'post',
            type: 'json',
            loading: true,
            data: this.getSubmitData(),
            success: (res) => {
              this.$message.success(this.$tt('tip_submit_success'))
              this.return_emit(null, "reload")
              this.dialogTip = true
              this.dialogTipInfo = res.data

            }
          })
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });

    },
  }
};

</script>
<style></style>
